'use client'

import { useEffect } from 'react'
import { MoreHorizontal, PlusCircle } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { useToast } from '@/components/ui/use-toast'
import RouterHook from '@/components/RouterHook'
import Loading from '@/components/Loading'
import useRequest from '@/utils/request'
import common from '@/utils/common'
import { useDispatch, useSelector } from 'react-redux'
import { selectCurProject } from '@/store/project-slice'
import {
  selectKeywords,
  selectIsLoading,
  selectPaginationConfig,
  fetchPaginatedData,
  setPaginationConfig,
  setIsLoading,
} from '@/store/keyword-slice'
import { Pagination, PaginationContent, PaginationItem } from '@/components/ui/pagination'
import { ChevronLeft, ChevronRight } from 'lucide-react'

export default function Keywords() {
  const { toast } = useToast()
  const curProject = useSelector(selectCurProject)
  const request = useRequest()
  const keywords = useSelector(selectKeywords)
  const isLoading = useSelector(selectIsLoading)
  const paginationConfig = useSelector(selectPaginationConfig)
  const dispatch = useDispatch()

  const delData = async data => {
    const res = await request.delete(`red_growth/keyword?project_id=${curProject.id}&id=${data.id}`)
    toast({
      title: `Keyword '${data.keyword}' has been deleted.`,
    })

    dispatch(
      fetchPaginatedData({
        project_id: curProject.id,
        current: paginationConfig.currentPage,
        pageSize: paginationConfig.perPage,
      })
    )
  }

  useEffect(() => {
    dispatch(setIsLoading(true))
    if (!curProject) {
      return
    }

    dispatch(
      fetchPaginatedData({
        project_id: curProject.id,
        current: paginationConfig.currentPage,
        pageSize: paginationConfig.perPage,
      })
    )
  }, [dispatch, paginationConfig, curProject])

  if (isLoading) {
    return <Loading />
  }

  if (keywords.length <= 0) {
    return (
      <div
        className="flex flex-1 items-center justify-center rounded-lg border border-dashed shadow-sm h-[500px] bg-card"
        x-chunk="dashboard-02-chunk-1"
      >
        <div className="flex flex-col items-center gap-1 text-center">
          <h3 className="text-2xl font-bold tracking-tight">You have no keywords</h3>
          <p className="text-sm text-muted-foreground">You can track your keywords as soon as you add a keyword.</p>
          <RouterHook path="/keywords/add">
            <Button className="mt-4">Add Keyword</Button>
          </RouterHook>
        </div>
      </div>
    )
  } else {
    return (
      <>
        <div className="flex items-center">
          <div className="mr-auto flex items-center gap-2">
            <RouterHook path="/keywords/add">
              <Button size="sm" className="h-8 gap-1">
                <PlusCircle className="h-3.5 w-3.5" />
                <span className="whitespace-nowrap">Add Keyword</span>
              </Button>
            </RouterHook>
          </div>
        </div>
        <Card x-chunk="dashboard-06-chunk-0">
          <CardHeader>
            <CardTitle>Keywords</CardTitle>
            <CardDescription>
              Your current keywords are listed below. You will receive an email whenever these are found (usually within
              a few minutes).
            </CardDescription>
          </CardHeader>
          <CardContent>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Keyword</TableHead>
                  <TableHead>Enabled</TableHead>
                  <TableHead className="hidden md:table-cell">Hits last 24h</TableHead>
                  <TableHead className="hidden md:table-cell">Created at</TableHead>
                  <TableHead>
                    <span className="sr-only">Actions</span>
                  </TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {keywords.map(keyword => {
                  return (
                    <TableRow key={keyword.id}>
                      <TableCell className="font-medium">{keyword.keyword}</TableCell>
                      <TableCell>
                        <Badge variant="outline">{keyword.status === '2' ? 'Active' : 'Draft'}</Badge>
                      </TableCell>
                      <TableCell className="hidden md:table-cell">{keyword.hits_24h}</TableCell>
                      <TableCell className="hidden md:table-cell">
                        {common.formatUnixTimestamp(keyword.createtime)}
                      </TableCell>
                      <TableCell>
                        <DropdownMenu>
                          <DropdownMenuTrigger asChild>
                            <Button aria-haspopup="true" size="icon" variant="ghost">
                              <MoreHorizontal className="h-4 w-4" />
                              <span className="sr-only">Toggle menu</span>
                            </Button>
                          </DropdownMenuTrigger>
                          <DropdownMenuContent align="end">
                            <DropdownMenuLabel>Actions</DropdownMenuLabel>
                            <RouterHook path={`/keywords/edit/${keyword.id}`}>
                              <DropdownMenuItem>Edit</DropdownMenuItem>
                            </RouterHook>
                            <DropdownMenuItem
                              onClick={() => {
                                delData(keyword)
                              }}
                            >
                              Delete
                            </DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </TableCell>
                    </TableRow>
                  )
                })}
              </TableBody>
            </Table>
          </CardContent>
          <CardFooter>
            <div className="w-full flex justify-between items-center">
              <div className="text-xs text-muted-foreground whitespace-nowrap">
                Showing{' '}
                <strong>
                  {paginationConfig.currentPage * paginationConfig.perPage - paginationConfig.perPage + 1}-
                  {paginationConfig.currentPage * paginationConfig.perPage > paginationConfig.total
                    ? paginationConfig.total
                    : paginationConfig.currentPage * paginationConfig.perPage}
                </strong>{' '}
                of <strong>{paginationConfig.total}</strong> keywords
              </div>
              <div>
                <Pagination>
                  <PaginationContent>
                    <PaginationItem>
                      <Button
                        variant="outline"
                        className="h-8 w-8 p-0"
                        onClick={() => {
                          dispatch(
                            setPaginationConfig({
                              ...paginationConfig,
                              currentPage: paginationConfig.currentPage - 1,
                            })
                          )
                        }}
                        disabled={paginationConfig.currentPage === 1}
                      >
                        <ChevronLeft className="h-4 w-4" />
                      </Button>
                    </PaginationItem>
                    <PaginationItem>
                      <Button
                        variant="outline"
                        className="h-8 w-8 p-0"
                        onClick={() => {
                          dispatch(
                            setPaginationConfig({
                              ...paginationConfig,
                              currentPage: paginationConfig.currentPage + 1,
                            })
                          )
                        }}
                        disabled={paginationConfig.currentPage === paginationConfig.lastPage}
                      >
                        <ChevronRight className="h-4 w-4" />
                      </Button>
                    </PaginationItem>
                  </PaginationContent>
                </Pagination>
              </div>
            </div>
          </CardFooter>
        </Card>
      </>
    )
  }
}
